import React, { useState, useEffect } from 'react';

import API_CONFIG from '../utils/apiConfig.js';

const ChannelTable = () => {
  // 状态定义
  const [configs, setConfigs] = useState([]);
  const [cameras, setCameras] = useState([]);
  const [selectedConfig, setSelectedConfig] = useState(null);
  const [mappings, setMappings] = useState([]);
  const [searchTerms, setSearchTerms] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);
  const [apiStatus, setApiStatus] = useState({});
  const [newConfigName, setNewConfigName] = useState('');
  const [isCreating, setIsCreating] = useState(false);
  const [virtualChannels, setVirtualChannels] = useState([1, 2, 3, 4, 5, 6, 7, 8]); // 使用ID数组替代计数器

  // API连接检查 - 更新为使用API_CONFIG
  const checkApiConnection = async () => {
    try {
      // 使用API_CONFIG的baseURL
      const response = await API_CONFIG.fetch('configs', {  
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });
      
      if (!response.ok) {
        console.warn(`API基础URL访问失败，状态码: ${response.status}`);
        showApiError('基础API路径不可访问，请检查后端服务是否运行');
      }
      
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('text/html')) {
        console.warn('API返回HTML而不是JSON');
        showApiError('API返回的是网页内容，而不是预期的数据格式');
      }
    } catch (error) {
      console.error('检查API连接时出错:', error);
      showApiError(`无法连接到API服务: ${error.message}`);
    }
  };

  const showApiError = (message) => {
    setError(prev => prev ? `${prev}\n${message}` : message);
  };

  // 数据加载
  const loadData = async () => {
    setIsLoading(true);
    setError(null);
    
    const defaultConfigs = [{ id: 1, config_name: '默认配置', mappings: [] }];
    let finalConfigs = defaultConfigs;
    let finalCameras = generateMockCameras();
    
    try {
      const [configsResult, camerasResult] = await Promise.allSettled([
        fetchConfigs(),
        fetchCameras()
      ]);
      
      if (configsResult.status === 'fulfilled' && configsResult.value) {
        finalConfigs = configsResult.value;
      } else {
        console.warn('使用模拟配置数据:', configsResult.reason);
        showApiError('获取配置失败，使用模拟数据');
      }
      
      if (camerasResult.status === 'fulfilled' && camerasResult.value) {
        finalCameras = camerasResult.value;
      } else {
        console.warn('使用模拟摄像头数据:', camerasResult.reason);
        showApiError('获取摄像头列表失败，使用模拟数据');
      }
      
    } catch (error) {
      console.error('数据加载失败:', error);
      showApiError('数据加载失败，使用模拟数据展示');
    } finally {
      setConfigs(finalConfigs);
      setCameras(finalCameras);
      setIsLoading(false);
      
      if (finalConfigs.length > 0) {
        const firstConfig = finalConfigs[0];
        const configWithMappings = {
          ...firstConfig,
          mappings: Array.isArray(firstConfig.mappings) ? firstConfig.mappings : []
        };
        
        setMappings(configWithMappings.mappings);
        setSelectedConfig(configWithMappings);
      }
      setIsLoading(false);
    }
  };

  // 获取配置
  const fetchConfigs = async () => {
    try {
      const response = await API_CONFIG.fetch('configs', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });
      
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('text/html')) {
        throw new Error('API返回HTML内容，路径可能错误');
      }
      
      const data = await response.json();
      
      if (Array.isArray(data)) {
        return data;
      } else if (data && typeof data === 'object') {
        return [data];
      } else {
        return [];
      }
    } catch (error) {
      console.error('获取配置失败:', error);
      setApiStatus(prev => ({ ...prev, configs: { status: 'error', error: error.message } }));
      
      return [{
        id: 1,
        config_name: '默认配置',
        mappings: [
          { channel_id: 1, camera_id: 2 },
          { channel_id: 2, camera_id: 3 },
          { channel_id: 3, camera_id: 4 },
          { channel_id: 4, camera_id: 5 },
          { channel_id: 5, camera_id: 6 },
          { channel_id: 6, camera_id: 7 },
          { channel_id: 7, camera_id: 8 },
          { channel_id: 8, camera_id: 9 }
        ]
      }];
    }
  };

  // 获取摄像头
  const fetchCameras = async () => {
    try {
      const response = await API_CONFIG.fetch('cameras', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });
      
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('text/html')) {
        console.warn('摄像头API返回HTML内容，使用模拟数据');
        return generateMockCameras();
      }
      
      const data = await response.json();
      return data || generateMockCameras();
    } catch (error) {
      console.error('获取摄像头列表失败:', error);
      return generateMockCameras();
    }
  };

  // 生成模拟摄像头
  const generateMockCameras = () => {
    const cameras = [];
    for (let i = 1; i <= 167; i++) {
      cameras.push({
        id: i,
        point_name: `物理摄像头 ${i}`,
        channel_number: i
      });
    }
    return cameras;
  };

  // 配置选择处理
  const handleConfigSelect = (config) => {
    if (!config) {
      setSelectedConfig(null);
      setMappings([]);
      setVirtualChannels([1, 2, 3, 4, 5, 6, 7, 8]); // 重置为默认虚拟通道
      return;
    }
    
    setSelectedConfig(config);
    console.log("Selected config:", config);
    
    // 更新映射数据
    const configMappings = Array.isArray(config.mappings) ? config.mappings : [];
    setMappings(configMappings);
    
    // 更新虚拟通道数组以匹配实际的映射记录
    if (configMappings.length > 0) {
      const channelIds = configMappings.map(mapping => mapping.channel_id);
      const uniqueChannelIds = [...new Set(channelIds)];
      
      // 总是更新虚拟通道数组以匹配当前配置的映射
      setVirtualChannels(uniqueChannelIds);
    } else {
      // 如果配置没有映射，重置为默认虚拟通道
      setVirtualChannels([1, 2, 3, 4, 5, 6, 7, 8]);
    }
  };

  // 更新映射
  const updateMapping = (virtualId, physicalId) => {
    let newMappings = [...mappings];
    const existingIndex = newMappings.findIndex(m => m.channel_id === virtualId);
    
    if (existingIndex >= 0) {
      newMappings[existingIndex] = { 
        ...newMappings[existingIndex], 
        camera_id: physicalId 
      };
    } else {
      newMappings.push({
        channel_id: virtualId,
        camera_id: physicalId
      });
    }
    
    setMappings(newMappings);
  };

  // 搜索处理
  const handleSearchChange = (virtualId, term) => {
    setSearchTerms(prev => ({
      ...prev,
      [virtualId]: term
    }));
  };

  // 增强保存映射的函数
  const saveMappings = async () => {
    if (!selectedConfig) return;
    
    setIsSaving(true);
    setError(null);
    try {
      const saveUrl = API_CONFIG.getURL('configs') + `/${selectedConfig.id}/mappings`;
      // 确保只发送当前有效的虚拟通道的映射
      const activeMappings = mappings.filter(mapping => 
        virtualChannels.includes(mapping.channel_id)
      );
      
      console.log('保存的映射数据:', activeMappings);
      console.log('有效的虚拟通道:', virtualChannels);
      
      const response = await fetch(saveUrl, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mappings: activeMappings }) // 只发送有效的映射
      });
      
      setApiStatus(prev => ({ ...prev, save: { status: response.status, url: saveUrl } }));
      
      if (!response.ok) {
        const updatedConfig = {
          ...selectedConfig,
          mappings: [...mappings]
        };
        
        const updatedConfigs = configs.map(c => 
          c.id === selectedConfig.id ? updatedConfig : c
        );
        
        setConfigs(updatedConfigs);
        setSelectedConfig(updatedConfig);
        
        try {
          const errorText = await response.text();
          console.warn('保存API错误详情:', errorText);
          alert(`保存失败: ${response.status} ${response.statusText}\n\n详细信息: ${errorText.substring(0, 200)}`);
        } catch (e) {
          alert(`保存失败: ${response.status} ${response.statusText}\n\n配置已在本地保存，但未同步到服务器`);
        }
        return;
      }
      
      try {
        const result = await response.json();
        console.log('保存成功:', result);
      } catch (jsonError) {
        console.warn('保存成功但响应不是JSON格式:', jsonError);
      }
      
      const updatedConfigsResult = await fetchConfigs();
      
      if (updatedConfigsResult.length > 0) {
        const configWithMappings = updatedConfigsResult.map(config => ({
          ...config,
          mappings: config.id === selectedConfig.id ? mappings : (Array.isArray(config.mappings) ? config.mappings : [])
        }));
        
        setConfigs(configWithMappings);
        
        const updatedConfig = configWithMappings.find(c => c.id === selectedConfig.id);
        if (updatedConfig) {
          setSelectedConfig(updatedConfig);
          setMappings(updatedConfig.mappings || []);
        }
      } else {
        const updatedConfig = {
          ...selectedConfig,
          mappings: [...mappings]
        };
        
        const updatedConfigs = configs.map(c => 
          c.id === selectedConfig.id ? updatedConfig : c
        );
        
        setConfigs(updatedConfigs);
        setSelectedConfig(updatedConfig);
        setMappings(mappings);
      }
      
      alert('映射配置保存成功！');
    } catch (error) {
      console.error('保存映射配置失败:', error);
      setApiStatus(prev => ({ ...prev, save: { status: 'error', error: error.message } }));
      
      const updatedConfig = {
        ...selectedConfig,
        mappings: [...mappings]
      };
      
      const updatedConfigs = configs.map(c => 
        c.id === selectedConfig.id ? updatedConfig : c
      );
      
      setConfigs(updatedConfigs);
      setSelectedConfig(updatedConfig);
      
      alert(`网络连接失败: ${error.message}\n\n配置已在本地保存，但无法同步到服务器`);
    } finally {
      setIsSaving(false);
    }
  };

  // 过滤摄像头
  const getFilteredCameras = (virtualId) => {
    const term = searchTerms[virtualId] || '';
    if (!term) return cameras;
    
    return cameras.filter(camera => 
      camera.point_name.toLowerCase().includes(term.toLowerCase()) ||
      camera.channel_number.toString().includes(term)
    );
  };

  // 添加新增通道的函数
  // 在addVirtualChannel函数后添加deleteVirtualChannel函数
  const addVirtualChannel = () => {
    // 生成新的唯一ID（比当前最大ID大1）
    const maxId = Math.max(...virtualChannels);
    setVirtualChannels(prev => [...prev, maxId + 1]);
  };
  
  // 修改删除虚拟通道的函数，确保能正确同步到数据库
  const deleteVirtualChannel = (virtualId) => {
    if (virtualChannels.length <= 1) {
      alert('至少保留一个虚拟通道');
      return;
    }
    
    // 首先从映射中移除该通道的映射
    setMappings(prev => {
      const updatedMappings = prev.filter(mapping => mapping.channel_id !== virtualId);
      return updatedMappings;
    });
    
    // 然后从虚拟通道数组中移除该ID
    setVirtualChannels(prev => prev.filter(id => id !== virtualId));
    
    // 强制立即保存到后端，确保数据库记录被删除
    if (selectedConfig) {
      // 不使用setTimeout，而是使用一个小延迟确保状态已更新
      setTimeout(() => {
        saveMappings();
      }, 0);
    }
  };
  
  // 生成默认配置名称
  const generateDefaultConfigName = () => {
    const configCount = configs.length;
    return `配置${configCount + 1}`;
  };

  // 创建新配置
  const createNewConfig = async () => {
    if (!newConfigName.trim()) {
      alert('请输入配置名称');
      return;
    }
    
    setIsCreating(true);
    try {
      const response = await API_CONFIG.fetch('configs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ config_name: newConfigName })
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '创建配置失败');
      }
      
      const result = await response.json();
      alert(result.message);
      
      await loadData();
      
      handleConfigSelect(result.config);
      
      setNewConfigName('');
      
    } catch (error) {
      console.error('创建配置错误:', error);
      alert(`创建配置失败: ${error.message}`);
    } finally {
      setIsCreating(false);
    }
  };

  // 副作用钩子
  useEffect(() => {
    if (configs.length > 0 && !newConfigName) {
      setNewConfigName(generateDefaultConfigName());
    }
  }, [configs, newConfigName]);

  useEffect(() => {
    checkApiConnection();
    loadData();
  }, []);

  if (isLoading) {
    return (
      <div className="camera-mapping-manager">
        <div style={{ padding: '20px', textAlign: 'center' }}>
          加载中...
        </div>
      </div>
    );
  }

  // 添加删除配置的函数
  const deleteConfig = async (configId) => {
    if (!window.confirm('确定要删除此配置吗？删除后将无法恢复。')) {
      return;
    }

    try {
      const response = await fetch(`${API_CONFIG.getURL('configs')}/${configId}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' }
      });

      // 增强错误处理 - 检查响应是否为JSON
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('text/html')) {
        throw new Error('API返回HTML而非JSON数据，请检查后端路由是否配置正确');
      }

      if (response.ok) {
        // 如果删除的是当前选中的配置，清除选中状态
        if (selectedConfig && selectedConfig.id === configId) {
          setSelectedConfig(null);
          setMappings([]);
        }
        
        // 重新加载配置列表
        await loadData();
        alert('配置删除成功');
      } else {
        let errorMessage = '删除配置失败';
        try {
          const errorData = await response.json();
          errorMessage = errorData.error || errorMessage;
        } catch (jsonError) {
          console.error('解析错误响应失败:', jsonError);
        }
        alert(errorMessage);
      }
    } catch (error) {
      console.error('删除配置失败:', error);
      alert(`删除配置失败: ${error.message}`);
    }
  };

  // 返回JSX渲染部分
  return (
    <div className="camera-mapping-manager" style={{
      padding: '20px',
      fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif',
      backgroundColor: '#fafbfc',
      minHeight: '100vh'
    }}>
      {/* 完整的UI渲染代码 */}
      <div style={{
        maxWidth: '100%',
        margin: '-10px auto 20px auto',
        background: '#ffffff',
        borderRadius: '8px',
        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.04)',
        overflow: 'hidden',
        border: '1px solid #eaecef'
      }}>
        {/* 头部配置选择区域 */}
        <div style={{
          padding: '10px 20px',
          borderBottom: '1px solid #eaecef',
          backgroundColor: '#fafbfc'
        }}>
          <h2 style={{
            margin: '0 0 20px 0',
            fontSize: '20px',
            fontWeight: '600',
            color: '#111827',
            textAlign: 'center'
          }}>管理摄像头映射配置</h2>
          
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            marginBottom: '5px',
            flexWrap: 'wrap'
          }}>
            <span style={{
              fontSize: '14px',
              color: '#374151',              
              fontWeight: '500'
            }}>选择摄像头映射配置：</span>
            <select
              onChange={(e) => handleConfigSelect(configs.find(c => c.id === parseInt(e.target.value)))}
              value={selectedConfig?.id || ""}
              style={{
                padding: '8px 12px',
                border: '1px solid #d1d5db',
                borderRadius: '6px',
                fontSize: '14px',
                backgroundColor: '#ffffff',
                color: '#111827',
                cursor: 'pointer',
                transition: 'border-color 0.2s ease',
                outline: 'none'
              }}
              onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
              onBlur={(e) => e.target.style.borderColor = '#d1d5db'}
            >
              <option value="">-- 请选择配置 --</option>
              {configs.map(config => (
                <option key={config.id} value={config.id}>
                  {config.config_name}
                </option>
              ))}
            </select>
            
            {/* 添加删除按钮 */}
            {selectedConfig && (
              <button
                onClick={() => deleteConfig(selectedConfig.id)}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#ef4444',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  fontSize: '14px',
                  cursor: 'pointer',
                  transition: 'background-color 0.2s ease'
                }}
                onMouseOver={(e) => e.target.style.backgroundColor = '#dc2626'}
                onMouseOut={(e) => e.target.style.backgroundColor = '#ef4444'}
              >
                删除
              </button>
            )}

            {/* 新建配置输入框和按钮 */}
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              marginLeft: 'auto'
            }}>
              <input
                type="text"
                value={newConfigName}
                onChange={(e) => setNewConfigName(e.target.value)}
                placeholder="新配置名称"
                style={{
                  padding: '8px 12px',
                  border: '1px solid #d1d5db',
                  borderRadius: '6px',
                  fontSize: '14px',
                  width: '120px',
                  outline: 'none',
                  transition: 'border-color 0.2s ease'
                }}
                onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                onBlur={(e) => e.target.style.borderColor = '#d1d5db'}
              />
              <button
                onClick={createNewConfig}
                disabled={isCreating}
                style={{
                  padding: '8px 12px',
                  backgroundColor: isCreating ? '#9ca3af' : '#10b981',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: isCreating ? 'not-allowed' : 'pointer',
                  fontSize: '14px',
                  fontWeight: '500',
                  transition: 'all 0.2s ease',
                  outline: 'none'
                }}
                onMouseOver={(e) => !isCreating && (e.target.style.backgroundColor = '#059669')}
                onMouseOut={(e) => !isCreating && (e.target.style.backgroundColor = '#10b981')}
              >
                {isCreating ? '创建中...' : '新建配置'}
              </button>
            </div>
          </div>
        </div>

        {error && (
          <div style={{
            padding: '12px 20px',
            backgroundColor: '#fef2f2',
            color: '#dc2626',
            borderBottom: '1px solid #fee2e2',
            fontSize: '14px',
            display: 'flex',
            alignItems: 'center',
            gap: '8px'
          }}>
            <span style={{ fontSize: '16px' }}>⚠️</span>
            <span><strong>错误：</strong>{error}</span>
          </div>
        )}

        {selectedConfig && (
          <div>
            {/* 操作栏 */}
            <div style={{
              padding: '10px 20px 5px 20px',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              borderBottom: '1px solid #eaecef',
              backgroundColor: '#ffffff'
            }}>
              <div>
                <h3 style={{
                  margin: 0,
                  fontSize: '14px',
                  color: '#111827',
                  fontWeight: '600'
                }}>
                  配置ID: {selectedConfig.id}
                </h3>
              </div>
              <div>
                <h3 style={{
                  margin: 0,
                  fontSize: '14px',
                  color: '#111827',
                  fontWeight: '600'
                }}>
                  配置名称: {selectedConfig.config_name}
                </h3>
              </div>
              
              {/* 将按钮放在一个div内，确保都靠右 */}
              <div style={{ display: 'flex', gap: '10px' }}>
                <button
                  onClick={addVirtualChannel}
                  style={{
                    padding: '8px 16px',
                    backgroundColor: '#8b5cf6',
                    color: 'white',
                    border: 'none',
                    borderRadius: '6px',
                    cursor: 'pointer',
                    fontSize: '14px',
                    fontWeight: '500',
                    transition: 'all 0.2s ease',
                    outline: 'none'
                  }}
                  onMouseOver={(e) => e.target.style.backgroundColor = '#7c3aed'}
                  onMouseOut={(e) => e.target.style.backgroundColor = '#8b5cf6'}
                >
                  新增通道
                </button>
                
                <button
                  onClick={saveMappings}
                  disabled={isSaving}
                  style={{
                    padding: '8px 16px',
                    backgroundColor: isSaving ? '#9ca3af' : '#2563eb',
                    color: 'white',
                    border: 'none',
                    borderRadius: '6px',
                    cursor: isSaving ? 'not-allowed' : 'pointer',
                    fontSize: '14px',
                    fontWeight: '500',
                    transition: 'all 0.2s ease',
                    outline: 'none'
                  }}
                  onMouseOver={(e) => !isSaving && (e.target.style.backgroundColor = '#1d4ed8')}
                  onMouseOut={(e) => !isSaving && (e.target.style.backgroundColor = '#2563eb')}
                >
                  {isSaving ? (
                    <span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <span style={{ animation: 'spin 1s linear infinite' }}>🔄</span>
                      保存中...
                    </span>
                  ) : (
                    '保存配置'
                  )}
                </button>
              </div>
            </div>

            {/* 映射表格 */}
            <div style={{ padding: '0' }}>
              <table style={{
                width: '100%',
                borderCollapse: 'collapse',
                fontSize: '14px'
              }}>
                <thead>
                  <tr style={{
                    backgroundColor: '#f9fafb',
                    borderBottom: '1px solid #eaecef'
                  }}>
                    <th style={{
                      padding: '12px 16px',
                      textAlign: 'left',
                      fontWeight: '600',
                      color: '#374151',
                      fontSize: '13px',
                      borderRight: '1px solid #eaecef'
                    }}>虚拟通道ID</th>
                    <th style={{
                      padding: '12px 16px',
                      textAlign: 'left',
                      fontWeight: '600',
                      color: '#374151',
                      fontSize: '13px',
                      borderRight: '1px solid #eaecef',
                      width: '25%'
                    }}>虚拟通道名称</th>
                    <th style={{
                      padding: '12px 16px',
                      textAlign: 'left',
                      fontWeight: '600',
                      color: '#374151',
                      fontSize: '13px',
                      borderRight: '1px solid #eaecef',
                      width: '45%'
                    }}>当前映射的物理摄像头</th>
                    <th style={{
                      padding: '12px 16px',
                      textAlign: 'center',
                      fontWeight: '600',
                      color: '#374151',
                      fontSize: '13px'
                    }}>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {virtualChannels.map(virtualId => {
                    const safeMappings = Array.isArray(mappings) ? mappings : [];
                    console.log("Safe mappings:", safeMappings);
                    const mapping = safeMappings.find(m => m.channel_id === virtualId);
                    const currentCameraId = mapping?.camera_id || '';
                    const currentCamera = cameras.find(c => c.id === currentCameraId);
                    const filteredCameras = getFilteredCameras(virtualId);
                    
                    return (
                      <tr key={virtualId} style={{
                        borderBottom: '1px solid #f1f5f9',
                        backgroundColor: '#ffffff',
                        transition: 'background-color 0.15s ease'
                      }}
                      onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#f8fafc'}
                      onMouseOut={(e) => e.currentTarget.style.backgroundColor = '#ffffff'}
                      >
                        <td style={{
                          padding: '12px 16px',
                          color: '#111827',
                          fontWeight: '500',
                          borderRight: '1px solid #f1f5f9'
                        }}>
                          {virtualId}
                        </td>
                        <td style={{
                          padding: '12px 16px',
                          color: '#4b5563',
                          borderRight: '1px solid #f1f5f9'
                        }}>
                          虚拟通道 {virtualId}
                        </td>
                        <td style={{
                          padding: '12px 16px',
                          borderRight: '1px solid #f1f5f9'
                        }}>
                          <select
                            value={currentCameraId}
                            onChange={(e) => updateMapping(virtualId, parseInt(e.target.value))}
                            style={{
                              padding: '8px 12px',
                              border: '1px solid #d1d5db',
                              borderRadius: '6px',
                              fontSize: '14px',
                              backgroundColor: '#ffffff',
                              width: '100%',
                              cursor: 'pointer',
                              transition: 'border-color 0.2s ease',
                              outline: 'none'
                            }}
                            onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                            onBlur={(e) => e.target.style.borderColor = '#d1d5db'}
                          >
                            <option value="">-- 请选择物理摄像头 --</option>
                            {filteredCameras.map(camera => (
                              <option key={camera.id} value={camera.id}>
                                {camera.point_name} (通道{camera.channel_number})
                              </option>
                            ))}
                          </select>
                        </td>
                        
                        <td style={{
                          padding: '12px 16px',
                          textAlign: 'center'
                        }}>
                          <button
                            onClick={() => deleteVirtualChannel(virtualId)}
                            style={{
                              padding: '6px 12px',
                              border: '1px solid #ef4444',
                              backgroundColor: '#ffffff',
                              color: '#ef4444',
                              borderRadius: '6px',
                              fontSize: '13px',
                              fontWeight: '500',
                              cursor: 'pointer',
                              transition: 'all 0.2s ease',
                              outline: 'none'
                            }}
                            onMouseOver={(e) => {
                              e.target.style.backgroundColor = '#ef4444';
                              e.target.style.color = '#ffffff';
                            }}
                            onMouseOut={(e) => {
                              e.target.style.backgroundColor = '#ffffff';
                              e.target.style.color = '#ef4444';
                            }}
                          >
                            删除
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ChannelTable;

// 增强保存映射的函数，确保只保存有效的映射
const saveMappings = async () => {
  if (!selectedConfig) return;
  
  setIsSaving(true);
  setError(null);
  try {
    const saveUrl = `${API_CONFIG.baseURL}/camera-configs/${selectedConfig.id}/mappings`;
    // 确保只发送当前有效的虚拟通道的映射
    const activeMappings = mappings.filter(mapping => 
      virtualChannels.includes(mapping.virtual_camera_id)
    );
    
    // 添加调试信息，方便追踪问题
    console.log('删除后准备保存的映射数量:', activeMappings.length);
    console.log('删除后有效的虚拟通道:', virtualChannels);
    
    // 确保发送的是完整的映射数组，即使为空
    const response = await fetch(saveUrl, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
      },
      body: JSON.stringify({
        mappings: activeMappings,
        // 添加时间戳防止缓存
        timestamp: new Date().getTime()
      })
    });
    
    setApiStatus(prev => ({ ...prev, save: { status: response.status, url: saveUrl } }));
    
    if (!response.ok) {
      try {
        const errorText = await response.text();
        console.error('保存API错误详情:', errorText);
        alert(`保存失败: ${response.status} ${response.statusText}\n\n详细信息: ${errorText.substring(0, 200)}`);
      } catch (e) {
        alert(`保存失败: ${response.status} ${response.statusText}\n\n配置已在本地保存，但未同步到服务器`);
      }
      return;
    }
    
    // 保存成功后重新加载配置，确保数据完全同步
    const updatedConfigsResult = await fetchConfigs();
    if (updatedConfigsResult.length > 0) {
      setConfigs(updatedConfigsResult);
      const updatedConfig = updatedConfigsResult.find(c => c.id === selectedConfig.id);
      if (updatedConfig) {
        setSelectedConfig(updatedConfig);
        setMappings(Array.isArray(updatedConfig.mappings) ? updatedConfig.mappings : []);
      }
    }
    
    alert('映射配置保存成功！');
    
  } catch (error) {
    console.error('保存映射配置失败:', error);
    alert(`保存失败: ${error.message}\n\n配置已在本地删除，但数据库记录可能仍存在`);
  } finally {
    setIsSaving(false);
  }
};
